package org.vectrics.recruiter.struts.tag;

import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Iterator;

import org.apache.ecs.html.A;
import org.apache.log4j.Logger;
import org.vectrics.DataException;
import org.vectrics.SystemException;
import org.vectrics.common.db.DataUtils;
import org.vectrics.common.html.BorderTable;
import org.vectrics.common.html.Cell;
import org.vectrics.common.html.Row;
import org.vectrics.common.html.Table;
import org.vectrics.common.html.TextHelper;
import org.vectrics.hibernate.ThreadProperties;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.recruiter.RecruitServiceLocator;
import org.vectrics.recruiter.job.JobCandidate;
import org.vectrics.recruiter.user.CandidateInfo;
import org.vectrics.recruiter.user.Resume;
import org.vectrics.struts.Request;
import org.vectrics.struts.VectricsTagSupport;
import org.vectrics.user.Person;
import org.vectrics.user.User;

abstract public class UserResumeListTagAbstract extends VectricsTagSupport {

    private static final long serialVersionUID = -5553564775977862078L;

    static private transient Logger log = Logger.getLogger(UserResumeListTagAbstract.class);

    private SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");

    private String userId = null;

    private String width = "100%";

    private String jobCandidateId = null;

    public static String TABLE_FONT = "subFont";

    protected abstract String getRemoveResumeLink();

    protected abstract String getViewTextResumeLink();

    public UserResumeListTagAbstract() {
        super();
    }

    @Override
    public String makeStartTag() {
        log.debug("doStartTag() called");
        Request request = getRequest();

        JobCandidate jobCandidate = null;
        if (jobCandidateId != null) {
            jobCandidate = RecruitServiceLocator.getJobProvider().findJobCandidateById(new Long(jobCandidateId));
        }
        if (userId == null)
            throw new DataException("UserId property not set before rendering");

        Table box = new Table();
        box.setWidth(600);

        Cell contentCell = box.addRow().addCell();

        Collection resumes = null;
        try {
            if (log.isDebugEnabled()) {
                log.debug("doStartTag() - finding resumes from database, userId = " + userId);
            }
            Person person = CoreServiceLocator.getPersonService().findPersonById(new Long(userId));
            CandidateInfo candidate = RecruitServiceLocator.getRecruitUserService().findCandidateInfo(person);
            if (candidate != null) {
                resumes = candidate.getResumes();
                resumes = DataUtils.removeVoided(resumes);
            }

        } catch (Exception fe) {
            log.error("doStartTag() - data exception finding resumes", fe);
            throw new DataException("doStartTag() - data exception finding resumes", fe);
        }

        if (resumes == null || resumes.size() == 0) {
            contentCell.addElement(TextHelper.getFont("stdFont", "<br><i>No Resumes for this User</i>"));
        } else {
            log.debug("doStartTag() - making table to display jobs");
            Table listTable = new BorderTable();
            listTable.setWidth(width);
            contentCell.addElement(listTable);

            Row hdrRow = listTable.addRow();
            hdrRow.setDefaultBgImage(getContextPath() + "/site-graphics/tbl_hdr.gif");
            Cell hdrCell = hdrRow.addCell();
            if (jobCandidate != null) {
                hdrCell.addElement(TextHelper.getFont("tableHdrFont", "Selected for Job"));
            }
            hdrCell.addElement(TextHelper.getFont("tableHdrFont", "Date"));
            hdrCell = hdrRow.addCell();
            hdrCell.addElement(TextHelper.getFont("tableHdrFont", "Description"));
            hdrCell = hdrRow.addCell();
            hdrCell.addElement(TextHelper.getFont("tableHdrFont", "Type"));
            hdrCell = hdrRow.addCell();
            hdrCell.addElement(TextHelper.getFont("tableHdrFont", "Actions"));

            Iterator iter = resumes.iterator();
            while (iter.hasNext()) {
                Resume resume = (Resume) iter.next();

                log.debug("Reload resume to make sure it is current");
                resume = RecruitServiceLocator.getRecruitUserService().findResume(resume.getId());

                if (resume.getDocument() == null)
                    throw new SystemException("Resume had a null document.  Resume=" + resume.toString());

                if (resume.getVoided() == false) {
                    Row row = listTable.addRow();
                    Cell cell = null;

                    if (jobCandidate != null) {
                        cell = row.addCell();
                        if (jobCandidate.getResume() != null) {
                            if (resume.getId().equals(jobCandidate.getResume().getId())) {
                                cell.addElement(TextHelper.getFont("subFont", "Selected"));
                            }
                        }
                    }

                    cell = row.addCell();
                    cell.addElement(TextHelper.getFont("subFont", dateFormatter.format(resume.getLastUpdate())));

                    cell = row.addCell();
                    cell.addElement(TextHelper.getFont("subFont", resume.getName()));

                    String typeDesc = "Text";
                    log.debug("Finding document type");
                    if (resume.getDocument().getSavedFileName() == null) {
                        typeDesc = "No File";
                    } else {
                        if (resume.getDocument().getSavedFileName().toLowerCase().endsWith(".doc")) {
                            typeDesc = "Word Document";
                        } else if (resume.getDocument().getSavedFileName().toLowerCase().endsWith(".pdf")) {
                            typeDesc = "PDF";
                        } else if (resume.getDocument().getSavedFileName().toLowerCase().endsWith(".txt")) {
                            typeDesc = "Text";
                        } else {
                            typeDesc = "Unknown Format";
                        }
                    }
                    cell = row.addCell();
                    cell.addElement(TextHelper.getFont("subFont", typeDesc));

                    cell = row.addCell();
                    A retrieveLink = new A();
                    retrieveLink.setClass("subLink");
                    String domainIdStr = ThreadProperties.getDomain().getId().toString();
                    String savedFileName = resume.getDocument().getSavedFileName();
                    Person authPerson = CoreServiceLocator.getUserAuthService().getAuthorizedPerson(request);
                    authPerson = CoreServiceLocator.getPersonService().findPersonById(authPerson.getId());
                    User authUser = authPerson.getUser();
                    if (authUser == null)
                        throw new SystemException("UserResumeListTagAbstract - Could not find user object for person: "
                                + authPerson);
                    String userName = authUser.getUserName();
                    String password = authUser.getPassword();

                    retrieveLink.setHref(request.getContextPath() + "/retrievedocument/resume" + savedFileName
                            + "?resumeId=" + resume.getId() + "&domainId=" + domainIdStr + "&userName=" + userName
                            + "&password=" + password);
                    retrieveLink.setOnClick("OpenLarge(this.href, '" + resume.getId() + "'); return false");
                    retrieveLink.addElement("retrieve");
                    cell.addElement(retrieveLink);
                    cell.addElement(TextHelper.getFont("subFont", "&nbsp"));

                    A removeLink = new A();
                    removeLink.setClass("subLink");
                    removeLink.setHref(request.getContextPath() + getRemoveResumeLink() + "?resumeId=" + resume.getId()
                            + "&userId=" + userId);
                    removeLink.addElement("remove");
                    cell.addElement(removeLink);
                }
            }
        }

        log.debug("doStartTag() - done");
        return box.toString();

    }

    /**
     * @return Returns the userId.
     */
    public final String getUserId() {
        return userId;
    }

    /**
     * @param userId
     *            The userId to set.
     */
    public final void setUserId(final String userId) {
        if (log.isDebugEnabled()) {
            log.debug("User id set to: " + userId);
        }
        this.userId = userId;
    }

    /**
     * @return Returns the log.
     */
    public static Logger getLog() {
        return log;
    }

    /**
     * @param log
     *            The log to set.
     */
    public static void setLog(final Logger log) {
        UserResumeListTagAbstract.log = log;
    }

    /**
     * @return Returns the width.
     */
    public String getWidth() {
        return width;
    }

    /**
     * @param width
     *            The width to set.
     */
    public void setWidth(final String width) {
        this.width = width;
    }

}
